<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="JDBC, luckyzmj 计算机 网络安全 渗透测试">
    <meta name="description" content="无">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google-site-verification" content="pBWoGvVEP36FzzS4xIpoMejc5UKi3RKcxd9rWWcjiDg" />
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>JDBC | Long</title>

    <link rel="icon" type="image/jpeg" href="https://s1.ax1x.com/2020/05/17/YR20js.jpg">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;900&display=swap" rel="stylesheet" media="print" onload="this.media='all'">
    <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?aaa6c944b0ed07922901d7fc571a171d";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
    </script>
<meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="Long" type="application/atom+xml">

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="https://s1.ax1x.com/2020/05/17/YRWsYT.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Long</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/census">
          
          <i class="fas fa-layer-group" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>统计</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <i class="fas fa-paper-plane" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>时轴</span>
        </a>
      </li>
      
      <li>
        <a href="/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>分类</span>
        </a>
      </li>
      
      <li>
        <a href="/tags">
          
          <i class="fas fa-tag" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>标签</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-heartbeat" style="zoom: 0.6;"></i>
      
      <span>清单</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/List/music">
          
          <i class="fas fa-music" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>音乐</span>
        </a>
      </li>
      
      <li>
        <a href="/List/galleries">
          
          <i class="fas fa-image" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>相册</span>
        </a>
      </li>
      
      <li>
        <a href="/List/movies">
          
          <i class="fas fa-film" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>视频</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-envelope" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tools" class="waves-effect waves-light">
      
      <i class="fas fa-suitcase" style="zoom: 0.6;"></i>
      
      <span>百宝箱</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/Windows" class="waves-effect waves-light">
      
      <i class="fas fa-desktop" style="zoom: 0.6;"></i>
      
      <span>Windows</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-link" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="https://s1.ax1x.com/2020/05/17/YRWsYT.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Long</div>
        <div class="logo-desc">
            
            无
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-archive"></i>
			
			归档
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/census " style="margin-left:75px">
				  
				   <i class="fa fas fa-layer-group" style="position: absolute;left:50px" ></i>
			      
		          <span>统计</span>
                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-paper-plane" style="position: absolute;left:50px" ></i>
			      
		          <span>时轴</span>
                  </a>
                </li>
              
                <li>

                  <a href="/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
		          <span>分类</span>
                  </a>
                </li>
              
                <li>

                  <a href="/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tag" style="position: absolute;left:50px" ></i>
			      
		          <span>标签</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-heartbeat"></i>
			
			清单
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/List/music " style="margin-left:75px">
				  
				   <i class="fa fas fa-music" style="position: absolute;left:50px" ></i>
			      
		          <span>音乐</span>
                  </a>
                </li>
              
                <li>

                  <a href="/List/galleries " style="margin-left:75px">
				  
				   <i class="fa fas fa-image" style="position: absolute;left:50px" ></i>
			      
		          <span>相册</span>
                  </a>
                </li>
              
                <li>

                  <a href="/List/movies " style="margin-left:75px">
				  
				   <i class="fa fas fa-film" style="position: absolute;left:50px" ></i>
			      
		          <span>视频</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-envelope"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tools" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-suitcase"></i>
			
			百宝箱
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/Windows" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-desktop"></i>
			
			Windows
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-link"></i>
			
			友链
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/LuckyZmj/" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/LuckyZmj/" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/banner/1.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">JDBC</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        background-color: white;
        width: 345px;
        padding-left: 20px;
        border-radius: 10px;
        box-shadow: 0 10px 35px 2px rgba(0, 0, 0, .15), 0 5px 15px rgba(0, 0, 0, .07), 0 2px 5px -5px rgba(0, 0, 0, .1) !important;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }
    
    #toc-content {
        height: calc(100vh - 300px);
        overflow: scroll;

    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
        bottom: 120px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/JDBC/">
                                <span class="chip bg-color">JDBC</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/JDBC/" class="post-category">
                                JDBC
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-03-15
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2021-09-02
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    7k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    29 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="1-JDBC概念"><a href="#1-JDBC概念" class="headerlink" title="1.JDBC概念"></a>1.JDBC概念</h2><h3 id="1-1-JDBC的由来"><a href="#1-1-JDBC的由来" class="headerlink" title="1.1 JDBC的由来"></a>1.1 JDBC的由来</h3><p><img src="https://i.loli.net/2021/09/02/nhxBlGOqfu5AaUr.png" alt="image-20201020185614120"></p>
<p>   Sun公司定义了一套<strong>操纵数据库的接口规范(JDBC)</strong>,具体的实现由不同的数据库服务厂商;</p>
<p>一般程序访问一些硬件资源都需要安装驱动,比如我们使用声卡\网卡 就需要安装声卡驱动和网卡驱动,如果我们使用U盘,那么就需要安装U盘相关的驱动;</p>
<p>   同样的道理,如果我们使用java访问数据库,也需要安装相关的驱动包;</p>
<p>数据库运行在不同的操作系统下,比如windows,linux,unix,macos等等,同时数据库又有不同的厂家提供,比如mysql,oracle,sqlserver等,如果对于程序员来说,针对不同的数据库在不同的操作系统下,安装不同的驱动软件,那么成本会很高;</p>
<p>   所以,Sun公司制定了一套规则,这套规则就是用来java连接数据库的,然后不同的厂商自己实现定义个规则即可,对于程序员只了解规则核心内容,即可对不同的数据库进行操作,这套规则叫做JDBC;</p>
<h3 id="1-2-JDBC的好处"><a href="#1-2-JDBC的好处" class="headerlink" title="1.2 JDBC的好处"></a>1.2 JDBC的好处</h3><ol>
<li>开发者只需会调用JDBC接口中的方法即可，使用简单；</li>
<li>底层实现交给具体的<strong>数据库厂商</strong>来完成，与开发者解耦；</li>
<li>对于不同 的数据库，开发者使用同一套Java代码，进行少量的修改就可以访问其他JDBC支持的数据库（<strong>移植性好</strong>）；</li>
</ol>
<p>小结:</p>
<p>1.说出JDBC概念?</p>
  <pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1</span><span class="token punctuation">)</span>是java连接数据库的桥梁<span class="token punctuation">;</span>
<span class="token number">2</span><span class="token punctuation">)</span>jdbc是Sun公司抽出出来的一套操纵数据库的接口规范<span class="token punctuation">,</span>规范接口由不同的数据库服务器厂商去实现<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>



<hr style="height:10px;background-color:green;border:none;">

<h2 id="2-JDBC核心API的介绍"><a href="#2-JDBC核心API的介绍" class="headerlink" title="2.JDBC核心API的介绍"></a>2.JDBC核心API的介绍</h2><h4 id="2-1-JDBC会用到的包"><a href="#2-1-JDBC会用到的包" class="headerlink" title="2.1 JDBC会用到的包"></a>2.1 JDBC会用到的包</h4><ol>
<li>java.sql：JDBC访问数据库的基础包，在JavaSE中的包。如：java.sql.Connection</li>
<li>javax.sql： JDBC访问数据库的扩展包(x表示extension,扩展)</li>
<li>数据库的驱动，各大数据库厂商来实现。如：MySQL的驱动：com.mysql.jdbc.Driver</li>
</ol>
<h4 id="2-2-JDBC四个核心对象"><a href="#2-2-JDBC四个核心对象" class="headerlink" title="2.2 JDBC四个核心对象"></a>2.2 JDBC四个核心对象</h4><p>这几个类都是在java.sql包中(<strong>1类3接口</strong>)</p>
<ol>
<li><strong>DriverManager(类)</strong>:  数据库驱动管理类。这个类的作用：1）注册驱动; 2)创建java代码和数据库之间的连接，即获取Connection接口;</li>
<li><strong>Connection(接口)</strong>: 是一个接口, 建立数据库连接的一个接口。作用：建立数据库和java代码之间的连接。表示与数据库创建的连接</li>
<li><strong>Statement(接口)、PreparedStatement(接口)</strong> (解决安全隐患问题，比如sql注入的问题)： 数据库操作，向数据库发送sql语句。执行SQL语句的对象</li>
<li><strong>ResultSet</strong>(接口): 结果集或一张虚拟表。 Statement 发送sql语句，得到的结果 封装在 ResultSet 中。</li>
</ol>
<h4 id="2-3-JDBC访问数据库的步骤"><a href="#2-3-JDBC访问数据库的步骤" class="headerlink" title="2.3 JDBC访问数据库的步骤"></a>2.3 JDBC访问数据库的步骤</h4><p><span style="background-color:red">PPT演示：</span></p>
<ol>
<li>由DriverManager注册驱动程序；</li>
<li>创建和数据库的连接对象Connection；</li>
<li>由客户端发送SQL语句给服务器执行，SQL语句封装成Statement对象；</li>
<li>查询到的结果集封装成ResultSet对象；</li>
<li>在客户端可以从ResultSet中取出数据，处理结果集；</li>
<li>释放资源，关闭连接对象；</li>
</ol>
<hr style="height:10px;background-color:green;border:none;">

<h2 id="3-注册驱动"><a href="#3-注册驱动" class="headerlink" title="3.注册驱动"></a>3.注册驱动</h2><h4 id="3-1注册驱动"><a href="#3-1注册驱动" class="headerlink" title="3.1注册驱动"></a>3.1注册驱动</h4><h5 id="1-DriverManager显式注册-理解"><a href="#1-DriverManager显式注册-理解" class="headerlink" title="1) DriverManager显式注册(理解)"></a>1) DriverManager显式注册(理解)</h5><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">registerDriver</span><span class="token punctuation">(</span><span class="token class-name">Driver</span> driver<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//向 DriverManager 注册给定驱动程序。 </span>
<span class="token comment">//获取所有注册的驱动类</span>
<span class="token keyword">static</span> <span class="token class-name">Enumeration</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Driver</span><span class="token punctuation">&gt;</span></span> <span class="token function">getDrivers</span><span class="token punctuation">(</span><span class="token punctuation">)</span> 
          获取带有当前调用者可以访问的所有当前已加载 JDBC 驱动程序的 <span class="token class-name">Enumeration</span>。 <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testRegister</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">{</span>
    <span class="token comment">//1)显式注册驱动</span>
    <span class="token class-name">DriverManager</span><span class="token punctuation">.</span><span class="token function">registerDriver</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Driver</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//2)获取注册的驱动</span>
    <span class="token class-name">Enumeration</span><span class="token generics"><span class="token punctuation">&lt;</span>java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span><span class="token class-name">Driver</span><span class="token punctuation">&gt;</span></span> drivers <span class="token operator">=</span> <span class="token class-name">DriverManager</span><span class="token punctuation">.</span><span class="token function">getDrivers</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//3)遍历</span>
    <span class="token keyword">while</span><span class="token punctuation">(</span>drivers<span class="token punctuation">.</span><span class="token function">hasMoreElements</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>drivers<span class="token punctuation">.</span><span class="token function">nextElement</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>说明:对于mysql不建议使用DriverManger的显式注册方式,会造成驱动2次注册,造成内存浪费;</p>
<p>注册2次的原因：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Driver</span>  <span class="token keyword">implements</span> java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span><span class="token class-name">Driver</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token class-name">Driver</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">static</span> <span class="token punctuation">{</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            <span class="token comment">//在类被加载的时候，静态代码块就注册了一次了</span>
            <span class="token class-name">DriverManager</span><span class="token punctuation">.</span><span class="token function">registerDriver</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Driver</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">SQLException</span> var1<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span><span class="token string">"Can't register driver!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>说明:使用DriverManager.registerDriver()会导致驱动类注册2次,浪费内存;</p>
<h4 id="3-2-隐式注册驱动"><a href="#3-2-隐式注册驱动" class="headerlink" title="3.2  隐式注册驱动"></a>3.2  隐式注册驱动</h4><h5 id="1-类加载实现驱动注册"><a href="#1-类加载实现驱动注册" class="headerlink" title="1)类加载实现驱动注册"></a>1)类加载实现驱动注册</h5><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//隐式注册</span>
<span class="token class-name">Class</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"com.mysql.jdbc.Driver"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span> <span class="token punctuation">{</span>
    <span class="token comment">//1)隐式注册</span>
    <span class="token class-name">Class</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"com.mysql.jdbc.Driver"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//2)获取注册的驱动</span>
    <span class="token class-name">Enumeration</span><span class="token generics"><span class="token punctuation">&lt;</span>java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span><span class="token class-name">Driver</span><span class="token punctuation">&gt;</span></span> drivers <span class="token operator">=</span> <span class="token class-name">DriverManager</span><span class="token punctuation">.</span><span class="token function">getDrivers</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//3)遍历</span>
    <span class="token keyword">while</span><span class="token punctuation">(</span>drivers<span class="token punctuation">.</span><span class="token function">hasMoreElements</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>drivers<span class="token punctuation">.</span><span class="token function">nextElement</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-SPI机制自动加载-了解即可"><a href="#2-SPI机制自动加载-了解即可" class="headerlink" title="2)SPI机制自动加载(了解即可)"></a>2)SPI机制自动加载(了解即可)</h5><p>​    java6之后引入了SPI机制,jdbc利用SPI机制会自动加载实现了Driver的接口实现类;</p>
<p>​    所以导入驱动包后无需配置,直接使用即可;</p>
<p>小结:</p>
<p>如何通过jdbc注册数据库驱动?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1</span><span class="token punctuation">)</span>显式注册: DriverManager<span class="token punctuation">.</span>registerDriver<span class="token punctuation">(</span>驱动类对象<span class="token punctuation">)</span><span class="token comment">-----&gt;2次注册,浪费内存</span>
<span class="token number">2</span><span class="token punctuation">)</span>隐式注册: Class<span class="token punctuation">.</span>forName<span class="token punctuation">(</span>驱动类的全限定名称<span class="token punctuation">)</span><span class="token comment">----&gt;只注册一次</span>
<span class="token number">3</span><span class="token punctuation">)</span>jdb spi机制<span class="token punctuation">,</span>自动加载services包下接口文件<span class="token punctuation">,</span>自动加载<span class="token punctuation">,</span>无需手动加载<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">



<h2 id="4-获取连接"><a href="#4-获取连接" class="headerlink" title="4.获取连接"></a>4.获取连接</h2><h3 id="API介绍"><a href="#API介绍" class="headerlink" title="API介绍"></a>API介绍</h3><p><code>java.sql.DriverManager</code>类中有如下方法获取数据库连接</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">static</span> <span class="token class-name">Connection</span> <span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token class-name">String</span> url<span class="token punctuation">,</span> <span class="token class-name">String</span> user<span class="token punctuation">,</span> <span class="token class-name">String</span> password<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//试图建立到给定数据库 URL 的连接。 </span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h4 id="参数说明"><a href="#参数说明" class="headerlink" title="参数说明"></a>参数说明</h4><ol>
<li><code>String url</code>：连接数据库的URL，用于说明连接数据库的位置</li>
<li><code>String user</code>：数据库的账号</li>
<li><code>String password</code>：数据库的密码</li>
</ol>
<p>url格式:</p>
<p>主协议:子协议://localhost:3306/test?参数=参数值&amp;…&amp;…..</p>
<p>举例:</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">jdbc:mysql:<span class="token comment">//localhost:3306/day05?useUnicode=true&amp;characterEncoding=utf8</span>
如果连接的时本地且端口号是<span class="token number">3306</span>
jdbc:mysql:<span class="token comment">///day05?useUnicode=true&amp;characterEncoding=utf8</span>

说明:如果连接的时本地localhost<span class="token punctuation">,</span>且端口默认为<span class="token number">3306</span> 那么可以ip和端口可以省略不写<span class="token punctuation">;</span>
eg:jdbc:mysql:<span class="token comment">///day05</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>注意事项:</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">如果数据出现乱码需要加上参数: ?useUnicode=true&amp;characterEncoding=utf8，表示让数据库以UTF8编码来处理数据。
如: jdbc:mysql://localhost:3306/day04_db?useUnicode=true&amp;characterEncoding=utf8<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>练习1:使用jdbc连接day05_2数据库</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test4</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">,</span> <span class="token class-name">SQLException</span> <span class="token punctuation">{</span>
    <span class="token comment">//1.注册驱动</span>
    <span class="token class-name">Class</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"com.mysql.jdbc.Driver"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//2.获取连接对象</span>
    <span class="token class-name">String</span> url<span class="token operator">=</span><span class="token string">"jdbc:mysql://localhost:3306/day05_2"</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> user<span class="token operator">=</span><span class="token string">"root"</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> pwd<span class="token operator">=</span><span class="token string">"1234"</span><span class="token punctuation">;</span>
    <span class="token class-name">Connection</span> conn <span class="token operator">=</span> <span class="token class-name">DriverManager</span><span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span>url<span class="token punctuation">,</span> user<span class="token punctuation">,</span> pwd<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>conn<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>小结:</p>
<p>1.JDBC获取数据库连接使用哪个API？</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">DriverManager<span class="token punctuation">.</span>getConnection<span class="token punctuation">(</span>url<span class="token punctuation">,</span><span class="token keyword">user</span><span class="token punctuation">,</span>password<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>2.通过JDBC连接mysql的URL写法？</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">jdbc:mysql:<span class="token comment">//ip地址:端口号/库</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">

<h2 id="5-JDBC实现对单表数据增-删-改操作"><a href="#5-JDBC实现对单表数据增-删-改操作" class="headerlink" title="5.JDBC实现对单表数据增,删,改操作"></a>5.JDBC实现对单表数据增,删,改操作</h2><h5 id="API介绍-1"><a href="#API介绍-1" class="headerlink" title="API介绍"></a>API介绍</h5><p>获取Statement对象</p>
<p>在<code>java.sql.Connection</code>接口中有如下方法获取到<code>Statement</code>对象</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Statement</span> <span class="token function">createStatement</span><span class="token punctuation">(</span><span class="token punctuation">)</span> 
创建一个 <span class="token class-name">Statement</span> 对象来将 SQL 语句发送到数据库<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>Statement的API介绍</p>
<ol>
<li><pre><code class="java">int executeUpdate(String sql)
根据执行的DML（INSERT、UPDATE、DELETE）语句，返回受影响的行数
<pre class="line-numbers language-none"><code class="language-none">
2. ```java
   ResultSet executeQuery(String sql)
   根据查询语句返回结果集,只能执行SELECT语句<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>


</code></pre>
</li>
</ol>
<h4 id="使用步骤"><a href="#使用步骤" class="headerlink" title="使用步骤"></a>使用步骤</h4><ol>
<li>注册驱动</li>
<li>获取连接</li>
<li>获取Statement对象</li>
<li>使用Statement对象执行SQL语句</li>
<li>释放资源</li>
</ol>
<p>练习题:对user表中数据实现增删改操作</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test6</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">,</span> <span class="token class-name">SQLException</span> <span class="token punctuation">{</span>
    <span class="token comment">//1.注册驱动</span>
    <span class="token class-name">Class</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"com.mysql.jdbc.Driver"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//2.获取连接</span>
    <span class="token class-name">String</span> url<span class="token operator">=</span><span class="token string">"jdbc:mysql:///day05_2"</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> user<span class="token operator">=</span><span class="token string">"root"</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> pwd<span class="token operator">=</span><span class="token string">"1234"</span><span class="token punctuation">;</span>
    <span class="token class-name">Connection</span> conn <span class="token operator">=</span> <span class="token class-name">DriverManager</span><span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span>url<span class="token punctuation">,</span> user<span class="token punctuation">,</span> pwd<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//3.获取发送sql语句的对象Statement</span>
    <span class="token class-name">Statement</span> stm <span class="token operator">=</span> conn<span class="token punctuation">.</span><span class="token function">createStatement</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//4.发送sql语句,获取受影响行数</span>
    <span class="token comment">//1.测试插入 jdbc事务默认自动提交</span>
    <span class="token comment">//String sql="insert into user values(null,'likaiyuan','666')";</span>
    <span class="token comment">//测试更新</span>
    <span class="token comment">//String sql="update user set username='jialili',password='888' where id=4";</span>
    <span class="token class-name">String</span> sql<span class="token operator">=</span><span class="token string">"delete from user where id=3"</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> count <span class="token operator">=</span> stm<span class="token punctuation">.</span><span class="token function">executeUpdate</span><span class="token punctuation">(</span>sql<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>count<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">// 1</span>
    <span class="token comment">//5.释放资源</span>
    stm<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    conn<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">

<p>小结:</p>
<p>jdbc实现增删改流程?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1</span><span class="token punctuation">)</span>注册驱动 : Class<span class="token punctuation">.</span>forName<span class="token punctuation">(</span><span class="token string">"com.mysql.jdbc.Driver"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token number">2</span><span class="token punctuation">)</span>获取连接:Connection conn<span class="token operator">=</span> DriverManager<span class="token punctuation">.</span>getConnection<span class="token punctuation">(</span>url<span class="token punctuation">,</span><span class="token keyword">user</span><span class="token punctuation">,</span>pwd<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token number">3</span><span class="token punctuation">)</span>获取发送<span class="token keyword">sql</span>语句的对象Statement:  Statement stm<span class="token operator">=</span>conn<span class="token punctuation">.</span>createStatement<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token number">4</span><span class="token punctuation">)</span>发送<span class="token keyword">sql</span>: <span class="token keyword">int</span> count<span class="token operator">=</span>stm<span class="token punctuation">.</span>executeUpdate<span class="token punctuation">(</span><span class="token keyword">sql</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token number">5</span><span class="token punctuation">)</span>释放资源: stm<span class="token punctuation">.</span><span class="token keyword">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>conn<span class="token punctuation">.</span><span class="token keyword">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>





<h2 id="6-JDBC实现对单表数据查询"><a href="#6-JDBC实现对单表数据查询" class="headerlink" title="6.JDBC实现对单表数据查询"></a>6.JDBC实现对单表数据查询</h2><h3 id="6-1-jdbc单表查询操作"><a href="#6-1-jdbc单表查询操作" class="headerlink" title="6.1.jdbc单表查询操作"></a>6.1.jdbc单表查询操作</h3><blockquote>
<p>ResultSet rs = stm.executeQuery(sql);</p>
</blockquote>
<p>JDBC通过statement执行sql后,会将查询的结果封装到ResultSet下;</p>
<h4 id="1-ResultSet的原理"><a href="#1-ResultSet的原理" class="headerlink" title="1) ResultSet的原理"></a>1) ResultSet的原理</h4><p>ResultSet类似之前学过的游标:</p>
<ol>
<li>ResultSet内部有一个指针,刚开始记录开始位置</li>
<li>调用next方法, ResultSet内部指针会移动到下一行数据</li>
<li>我们可以通过ResultSet得到一行数据 getXxx得到某列数据</li>
</ol>
<p>其实ResultSet获取数据的API是有规律的get后面加数据类型。我们统称<code>getXXX()</code></p>
<p>练习:完成对user表中所有数据的查询</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test7</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">,</span> <span class="token class-name">SQLException</span> <span class="token punctuation">{</span>
    <span class="token comment">//1.注册驱动</span>
    <span class="token class-name">Class</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"com.mysql.jdbc.Driver"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//2.获取连接对象</span>
    <span class="token class-name">String</span> url<span class="token operator">=</span><span class="token string">"jdbc:mysql:///day05_2"</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> user<span class="token operator">=</span><span class="token string">"root"</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> pwd<span class="token operator">=</span><span class="token string">"1234"</span><span class="token punctuation">;</span>
    <span class="token class-name">Connection</span> conn <span class="token operator">=</span> <span class="token class-name">DriverManager</span><span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span>url<span class="token punctuation">,</span> user<span class="token punctuation">,</span> pwd<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//3.获取发送sql的对象</span>
    <span class="token class-name">Statement</span> stm <span class="token operator">=</span> conn<span class="token punctuation">.</span><span class="token function">createStatement</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//4.发送select语句</span>
    <span class="token class-name">String</span> sql<span class="token operator">=</span><span class="token string">"select * from user"</span><span class="token punctuation">;</span>
    <span class="token class-name">ResultSet</span> rs <span class="token operator">=</span> stm<span class="token punctuation">.</span><span class="token function">executeQuery</span><span class="token punctuation">(</span>sql<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//5.解析结果集</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span>rs<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">int</span> id <span class="token operator">=</span> rs<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> username <span class="token operator">=</span> rs<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> password <span class="token operator">=</span> rs<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>id<span class="token operator">+</span>username<span class="token operator">+</span>password<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token comment">//6.关闭资源,释放连接</span>
    rs<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    stm<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    conn<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="6-2-jdbc查询小结"><a href="#6-2-jdbc查询小结" class="headerlink" title="6.2.jdbc查询小结"></a>6.2.jdbc查询小结</h3><p>1.jdbc查询使用步骤?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1</span><span class="token punctuation">)</span>注册驱动
<span class="token number">2</span><span class="token punctuation">)</span>获取连接对象
<span class="token number">3</span><span class="token punctuation">)</span>获取发送<span class="token keyword">sql</span>的对象Statement<span class="token punctuation">;</span>
<span class="token number">4</span><span class="token punctuation">)</span>发送<span class="token keyword">sql</span><span class="token punctuation">,</span>获取结果集<span class="token punctuation">;</span> ResultSet rs<span class="token operator">=</span> stm<span class="token punctuation">.</span>executeQuery<span class="token punctuation">(</span><span class="token keyword">sql</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token number">5</span><span class="token punctuation">)</span>解析结果集<span class="token punctuation">,</span>获取数据
<span class="token number">6</span><span class="token punctuation">)</span>关闭资源<span class="token punctuation">,</span>释放连接<span class="token punctuation">(</span><span class="token number">3</span>个<span class="token keyword">close</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>2.ResultSet如何获取数据？</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1</span><span class="token punctuation">)</span>调用<span class="token keyword">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span>方法获取某一行的记录
<span class="token number">2</span><span class="token punctuation">)</span>通过getXXX<span class="token punctuation">(</span>字段索引位<span class="token punctuation">)</span><span class="token punctuation">;</span>getXXX<span class="token punctuation">(</span>字段名称<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">



<h2 id="7-编写JDBC工具类"><a href="#7-编写JDBC工具类" class="headerlink" title="7.编写JDBC工具类"></a>7.编写JDBC工具类</h2><p>练习:在src资源路径下创建jdbc.properties配置文件,并通过Properties类加载配置,实现参数加载</p>
<p>​        说明:1.添加配置文件 2.类加载器加载配置文件 3.Properties对象动态获取配置信息 4.初始化连接对象;</p>
<h3 id="1-创建jdbc-properties文件"><a href="#1-创建jdbc-properties文件" class="headerlink" title="1.创建jdbc.properties文件"></a>1.创建jdbc.properties文件</h3><pre class="line-numbers language-properties" data-language="properties"><code class="language-properties"><span class="token attr-name">url</span><span class="token punctuation">=</span><span class="token attr-value">jdbc:mysql:///day05_2</span>
<span class="token attr-name">user</span><span class="token punctuation">=</span><span class="token attr-value">root</span>
<span class="token attr-name">pwd</span><span class="token punctuation">=</span><span class="token attr-value">1234</span>
<span class="token attr-name">driverClass</span><span class="token punctuation">=</span><span class="token attr-value">com.mysql.jdbc.Driver</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="2-封装工具类"><a href="#2-封装工具类" class="headerlink" title="2.封装工具类"></a>2.封装工具类</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">JdbcUtil3</span> <span class="token punctuation">{</span>

    <span class="token comment">/**
     * 参数提取全局,方便修改维护
     */</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token class-name">String</span> url<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token class-name">String</span> user<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token class-name">String</span> pwd<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token class-name">String</span> driverClass<span class="token punctuation">;</span>

    <span class="token comment">//驱动类只加载一次</span>
    <span class="token keyword">static</span> <span class="token punctuation">{</span>
        <span class="token comment">//1.加载配置文件,初始化数据库连接参数</span>
        <span class="token comment">//new FileInputStream("src/jdbc.properties");</span>
        <span class="token class-name">InputStream</span> in <span class="token operator">=</span> <span class="token class-name">JdbcUtil3</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getResourceAsStream</span><span class="token punctuation">(</span><span class="token string">"jdbc.properties"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Properties</span> properties <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Properties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            properties<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span>in<span class="token punctuation">)</span><span class="token punctuation">;</span>
            url<span class="token operator">=</span>properties<span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"url"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            user<span class="token operator">=</span>properties<span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"user"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            pwd<span class="token operator">=</span>properties<span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"pwd"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            driverClass<span class="token operator">=</span>properties<span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"driverClass"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>


        <span class="token comment">//1.注册驱动</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            <span class="token class-name">Class</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span>driverClass<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ClassNotFoundException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * 获取连接对象
     * @return
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">Connection</span> <span class="token function">getConnction</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">//2.获取连接对象</span>
        <span class="token class-name">Connection</span> conn<span class="token operator">=</span><span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            conn <span class="token operator">=</span> <span class="token class-name">DriverManager</span><span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span>url<span class="token punctuation">,</span> user<span class="token punctuation">,</span> pwd<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">SQLException</span> throwables<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            throwables<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> conn<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="3、-关闭资源"><a href="#3、-关闭资源" class="headerlink" title="3、 关闭资源"></a>3、 关闭资源</h3><p>关闭资源的顺序:1.ResultSet结果集 2.Statement 3.Connection</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * 释放资源,关闭连接
 * @param rs
 * @param stm
 * @param conn
 */</span>
<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">close</span><span class="token punctuation">(</span><span class="token class-name">ResultSet</span> rs<span class="token punctuation">,</span> <span class="token class-name">Statement</span> stm<span class="token punctuation">,</span><span class="token class-name">Connection</span> conn<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>rs<span class="token operator">!=</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            rs<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">SQLException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"rs:"</span><span class="token operator">+</span>e<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>stm<span class="token operator">!=</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            stm<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">SQLException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"stm:"</span><span class="token operator">+</span>e<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>conn<span class="token operator">!=</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            conn<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">SQLException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"conn:"</span><span class="token operator">+</span>e<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="7-2工具类优化后代用查询方法"><a href="#7-2工具类优化后代用查询方法" class="headerlink" title="7.2工具类优化后代用查询方法"></a>7.2工具类优化后代用查询方法</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test8</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">{</span>
    <span class="token comment">//1.获取连接对象</span>
    <span class="token class-name">Connection</span> conn <span class="token operator">=</span> <span class="token class-name">JdbcUtil3</span><span class="token punctuation">.</span><span class="token function">getConnction</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//2.获取发送sql的对象</span>
    <span class="token class-name">Statement</span> stm <span class="token operator">=</span> conn<span class="token punctuation">.</span><span class="token function">createStatement</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//4.发送select语句</span>
    <span class="token class-name">String</span> sql<span class="token operator">=</span><span class="token string">"select * from user"</span><span class="token punctuation">;</span>
    <span class="token class-name">ResultSet</span> rs <span class="token operator">=</span> stm<span class="token punctuation">.</span><span class="token function">executeQuery</span><span class="token punctuation">(</span>sql<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//5.解析结果集</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span>rs<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">int</span> id <span class="token operator">=</span> rs<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> username <span class="token operator">=</span> rs<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> password <span class="token operator">=</span> rs<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>id<span class="token operator">+</span>username<span class="token operator">+</span>password<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token comment">//关闭资源</span>
    <span class="token class-name">JdbcUtil3</span><span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span>rs<span class="token punctuation">,</span>stm<span class="token punctuation">,</span>conn<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">



<h2 id="8、JDBC事务"><a href="#8、JDBC事务" class="headerlink" title="8、JDBC事务"></a>8、JDBC事务</h2><h4 id="1-API介绍"><a href="#1-API介绍" class="headerlink" title="1.API介绍"></a>1.API介绍</h4><p>Connection接口与事务相关的核心API:</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">void</span> <span class="token function">setAutoCommit</span><span class="token punctuation">(</span><span class="token keyword">boolean</span> autoCommit<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span><span class="token punctuation">;</span><span class="token comment">// true:自动提交 flase:手动提交</span>
<span class="token keyword">void</span> <span class="token function">commit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span><span class="token punctuation">;</span><span class="token comment">//提交事务</span>
<span class="token keyword">void</span> <span class="token function">rollback</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span><span class="token punctuation">;</span><span class="token comment">//回滚事务</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>注意：</p>
<p> 在jdbc事务操作中，事务的控制都是通过Connection对象完成的，当一个完整的业务操作前，我们首先使用<strong>conn.setAutoCommit(false)**来设置事务手动提交。</strong>默认情况下是true的，表示自动提交事务**，那么一条sql语句就是一个事务，默认提交事务。如果设置为false，那么表示开启事务，所有的sql语句就会都在一个事务中。</p>
<p>​      当业务操作完成之后，如果整个操作没有问题，我们需要使用conn.commit()来提交事务。当然了，如果出现了异常，我们需要使用conn.rollback()撤销所有的操作，所以出现异常，需要进行事务的回滚。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * 需求：以a给b转账100业务为例；
 */</span>
<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test9</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token punctuation">{</span>
    <span class="token comment">//1.获取连接对象</span>
    <span class="token class-name">Connection</span> conn <span class="token operator">=</span> <span class="token class-name">JdbcUtil3</span><span class="token punctuation">.</span><span class="token function">getConnction</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Statement</span> stm<span class="token operator">=</span><span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token comment">//2.设置事务手动提交</span>
        conn<span class="token punctuation">.</span><span class="token function">setAutoCommit</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//3.获取发送sql对象Statement</span>
        stm <span class="token operator">=</span> conn<span class="token punctuation">.</span><span class="token function">createStatement</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//4.发送sql</span>
        <span class="token class-name">String</span> out<span class="token operator">=</span><span class="token string">"update account set money=money-100 where name='a'"</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> in<span class="token operator">=</span><span class="token string">"update account set money=money+100 where name='b'"</span><span class="token punctuation">;</span>
        stm<span class="token punctuation">.</span><span class="token function">executeUpdate</span><span class="token punctuation">(</span>out<span class="token punctuation">)</span><span class="token punctuation">;</span>
        stm<span class="token punctuation">.</span><span class="token function">executeUpdate</span><span class="token punctuation">(</span>in<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//5.事务提交</span>
        conn<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">SQLException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>e<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//回滚</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            conn<span class="token punctuation">.</span><span class="token function">rollback</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">SQLException</span> throwables<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>throwables<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token keyword">finally</span> <span class="token punctuation">{</span>
         <span class="token class-name">JdbcUtil3</span><span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span>stm<span class="token punctuation">,</span>conn<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h2 id="9、PreparedStatement对象"><a href="#9、PreparedStatement对象" class="headerlink" title="9、PreparedStatement对象"></a>9、PreparedStatement对象</h2><h3 id="1-获取PreparedStatement对象"><a href="#1-获取PreparedStatement对象" class="headerlink" title="1.获取PreparedStatement对象"></a>1.获取PreparedStatement对象</h3><p>PreparedStatement是Statement的子接口，可以防止sql注入问题。可以通过Connection接口中的prepareStatement(sql)方法获得PreparedStatement的对象。</p>
<p>方法如下所示：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//创建一个 PreparedStatement 对象来将参数化的 SQL 语句发送到数据库 </span>
<span class="token class-name">PreparedStatement</span>	<span class="token function">prepareStatement</span><span class="token punctuation">(</span><span class="token class-name">String</span> sql<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>注意：sql提前创建好的。sql语句中需要参数。使用<strong>？</strong>进行占位。</p>
<p>举例：</p>
<p>select *from user where username=’zhangsan’ and password = ‘123456’;</p>
<p><strong>使用？进行占位</strong></p>
<p>select *from user where username=? and password = ?;</p>
<pre class="line-numbers language-markdown" data-language="markdown"><code class="language-markdown">步骤一：PreparedStatement  pstmt =  conn.prepareStatement(sql); -----需要你事先传递sql模板。如果sql需要参数，使用？进行占位。

步骤二：设置参数（执行sql之前）：pstmt.setXXX(int index, 要放入的值) -----根据不同类型的数据进行方法的选择。第一个参数index表示的是？出现的位置。<span class="token bold"><span class="token punctuation">**</span><span class="token content">从1开始计数，有几个问号，就需要传递几个参数</span><span class="token punctuation">**</span></span>。
方法的参数说明：
第一个参数：int index ;表示的是问号出现的位置。 问号是从1开始计数
第二个参数：给问号的位置传入的值。

步骤三、执行，不需要在传递sql了。
   pstmt.executeQuery();---执行select
   pstmt.executeUpdate();---执行insert，delete，update<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * **练习: 预编译实现插入用户名 liuyan ，密码123.**
 */</span>
<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test13</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">{</span>
    <span class="token class-name">Connection</span> conn <span class="token operator">=</span> <span class="token class-name">JdbcUtil3</span><span class="token punctuation">.</span><span class="token function">getConnction</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//获取预编译对象</span>
    <span class="token class-name">String</span> sql<span class="token operator">=</span><span class="token string">"insert into user values(null,?,?)"</span><span class="token punctuation">;</span>
    <span class="token class-name">PreparedStatement</span> pstm <span class="token operator">=</span> conn<span class="token punctuation">.</span><span class="token function">prepareStatement</span><span class="token punctuation">(</span>sql<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//设置参数</span>
    pstm<span class="token punctuation">.</span><span class="token function">setString</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token string">"liuyan"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    pstm<span class="token punctuation">.</span><span class="token function">setString</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token string">"123"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//发送参数,执行sql</span>
    <span class="token keyword">int</span> count <span class="token operator">=</span> pstm<span class="token punctuation">.</span><span class="token function">executeUpdate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>count<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//释放资源</span>
    <span class="token class-name">JdbcUtil3</span><span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span>pstm<span class="token punctuation">,</span>conn<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>小结:</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">1)statement与PreparedStatement区别?
statement sql不进行预编译,有sql注入的风险;
PreparedStatement sql进行预编译,防止sql注入;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>



<h2 id="10、jdbc调用存储过程"><a href="#10、jdbc调用存储过程" class="headerlink" title="10、jdbc调用存储过程"></a>10、jdbc调用存储过程</h2><p>JDBC调用存储过程API:</p>
<p>1）获取连接Connection的对象</p>
<p>2）使用连接Connection的对象调用连接Connection的对象接口中的方法获取CallableStatement接口对象</p>
<pre class="line-numbers language-JAVA" data-language="JAVA"><code class="language-JAVA">CallableStatement prepareCall(String sql) 创建一个 CallableStatement 对象来调用数据库存储过程。 
    参数：
	sql - 可以包含一个或多个 '?' 参数占位符的 SQL 语句。通常此语句是使用 JDBC 调用转义语法指定的。
    	说明：参数sql中书写的是存储过程语句，语法是固定的写法：
    		1）带参数的存储过程写法：
    		String sql="{call 存储过程名(?,?, ...)}";
			IN 参数值是使用继承自 PreparedStatement 的 set 方法设置的.
                   从左向右第一个占位符编号是 1，第二个占位符编号是2，依次递增。
             void setString(int parameterIndex, String x)将指定参数设置为给定Java String 值。 
             void setInt(int parameterIndex, int x)  将指定参数设置为给定 Java int 值。 
                参数：parameterIndex表示第几个占位符 x 表示给占位符赋的实际值
        	在执行存储过程之前，必须注册所有 OUT 参数的类型。注册参数类型使用registerOutParameter   			  方法来完成的。
               void registerOutParameter(int parameterIndex, int sqlType) 
         			按顺序位置 parameterIndex 将 OUT 参数注册为 JDBC 类型 sqlType。      
                   	参数：
                   	parameterIndex：第一个参数是 1，第二个参数是 2，依此类推
                   	sqlType：java.sql.Types 定义的 JDBC 类型代码。例如：Types.INTEGER
             语句执行完后，CallableStatement的getXXX方法将取回参数值:
			 int getInt(int parameterIndex) 以 Java 编程语言中 int 值的形式获取指定的 JDBC 					INTEGER 参数的值。 
                    参数：表示获取的值属于第几个占位符，上述占位符中属于第四个，所以这里写4
			
		2)　不带参数的储存过程的语法：
           String sql="{call 存储过程名}"; <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>3）使用CallableStatement接口的父接口PreparedStatement的方法执行存储过程的sql语句：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">boolean</span> <span class="token function">execute</span><span class="token punctuation">(</span><span class="token punctuation">)</span> 在此 <span class="token class-name">PreparedStatement</span> 对象中执行 SQL 语句，该语句可以是任何种类的 SQL 语句。 <span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>4)使用CallableStatement的getXXX方法获取回参数值:</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">int</span> <span class="token function">getInt</span><span class="token punctuation">(</span><span class="token keyword">int</span> parameterIndex<span class="token punctuation">)</span> 以 <span class="token class-name">Java</span> 编程语言中 <span class="token keyword">int</span> 值的形式获取指定的 JDBC的INTEGER 参数的值。 
    参数：表示获取的值属于第几个占位符，上述占位符中属于第四个，所以这里写<span class="token number">4</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>5）输出存储过程的结果</p>
<p>6）释放资源</p>
<p>数据准备:</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">/*
	参数：
		fromSub 从哪位用户转账
		toSub 转给的用户
		m 转账金额
		flag 标记，1表示转账成功  0表示转账失败
*/</span>
<span class="token comment">-- 存储过程sql</span>
<span class="token keyword">DELIMITER</span> $
<span class="token keyword">CREATE</span>  <span class="token keyword">procedure</span> transfer<span class="token punctuation">(</span><span class="token operator">in</span> fromSub <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token operator">in</span> toSub <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token operator">in</span> m <span class="token keyword">FLOAT</span><span class="token punctuation">,</span><span class="token keyword">OUT</span> flag <span class="token keyword">INT</span><span class="token punctuation">)</span>
<span class="token keyword">BEGIN</span>
		<span class="token comment">-- i1变量存储转出账的ROW_COUNT()结果</span>
        <span class="token keyword">declare</span> i1 <span class="token keyword">INT</span> <span class="token keyword">DEFAULT</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token comment">-- i2变量存储转入账的ROW_COUNT()结果</span>
        <span class="token keyword">declare</span> i2 <span class="token keyword">INT</span> <span class="token keyword">DEFAULT</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token keyword">START</span> <span class="token keyword">TRANSACTION</span><span class="token punctuation">;</span>
        <span class="token comment">-- 转出账 扣钱</span>
        <span class="token keyword">UPDATE</span> account <span class="token keyword">SET</span> money <span class="token operator">=</span> money <span class="token operator">-</span> m <span class="token keyword">WHERE</span> name<span class="token operator">=</span>fromSub<span class="token punctuation">;</span>
        <span class="token comment">-- 将ROW_COUNT()即上次修改影响的行数1保存到变量i1中</span>
        <span class="token keyword">SELECT</span> ROW_COUNT<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">INTO</span> i1<span class="token punctuation">;</span>
         <span class="token comment">-- 转入账 </span>
        <span class="token keyword">UPDATE</span> account <span class="token keyword">SET</span> money <span class="token operator">=</span> money <span class="token operator">+</span> m <span class="token keyword">WHERE</span> name<span class="token operator">=</span>toSub<span class="token punctuation">;</span>
        <span class="token comment">-- 将ROW_COUNT()即上次修改影响的行数1保存到变量i2中</span>
        <span class="token keyword">SELECT</span> ROW_COUNT<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">INTO</span> i2<span class="token punctuation">;</span>
        <span class="token keyword">IF</span> i1<span class="token operator">&gt;</span><span class="token number">0</span> <span class="token operator">AND</span> i2<span class="token operator">&gt;</span><span class="token number">0</span> <span class="token keyword">THEN</span>
        		<span class="token comment">-- 提交事务</span>
                <span class="token keyword">COMMIT</span><span class="token punctuation">;</span>
                <span class="token keyword">SET</span> flag <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
        <span class="token keyword">ELSE</span>
        		<span class="token comment">-- 回滚事务</span>
                <span class="token keyword">ROLLBACK</span><span class="token punctuation">;</span>
                <span class="token keyword">SET</span> flag <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token keyword">END</span> <span class="token keyword">IF</span><span class="token punctuation">;</span>
        <span class="token keyword">SELECT</span> CONCAT<span class="token punctuation">(</span>i1<span class="token punctuation">,</span><span class="token string">'---'</span><span class="token punctuation">,</span>i2<span class="token punctuation">)</span><span class="token punctuation">;</span>        
<span class="token keyword">END</span> $

<span class="token comment">-- mysql调用存储过程</span>
<span class="token keyword">call</span> transfer<span class="token punctuation">(</span><span class="token string">'tom'</span><span class="token punctuation">,</span><span class="token string">'rose'</span><span class="token punctuation">,</span><span class="token number">100</span><span class="token punctuation">,</span><span class="token variable">@flag</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>练习:JDBC代码调用存储过程实现转账业务;</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">/**
 * 练习:JDBC代码调用存储过程实现转账业务;
 */</span>
<span class="token variable">@Test</span>
<span class="token keyword">public</span> void test15<span class="token punctuation">(</span><span class="token punctuation">)</span> throws SQLException {
    Connection conn <span class="token operator">=</span> JdbcUtil3<span class="token punctuation">.</span>getConnction<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//获取存储过程的预编译对象</span>
    String <span class="token keyword">sql</span><span class="token operator">=</span><span class="token string">"{call transfer(?,?,?,?)}"</span><span class="token punctuation">;</span>
    CallableStatement cstm <span class="token operator">=</span> conn<span class="token punctuation">.</span>prepareCall<span class="token punctuation">(</span><span class="token keyword">sql</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//设置入参</span>
    cstm<span class="token punctuation">.</span>setString<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token string">"a"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    cstm<span class="token punctuation">.</span>setString<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token string">"b"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    cstm<span class="token punctuation">.</span>setFloat<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">200</span>f<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//注册出参</span>
    cstm<span class="token punctuation">.</span>registerOutParameter<span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token keyword">Types</span><span class="token punctuation">.</span><span class="token keyword">INTEGER</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//发送参数,调用存储过程</span>
    cstm<span class="token punctuation">.</span><span class="token keyword">execute</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//获取出参</span>
    <span class="token keyword">int</span> flag <span class="token operator">=</span> cstm<span class="token punctuation">.</span>getInt<span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    System<span class="token punctuation">.</span><span class="token keyword">out</span><span class="token punctuation">.</span>println<span class="token punctuation">(</span>flag<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//释放资源</span>
    JdbcUtil3<span class="token punctuation">.</span><span class="token keyword">close</span><span class="token punctuation">(</span><span class="token boolean">null</span><span class="token punctuation">,</span>cstm<span class="token punctuation">,</span>conn<span class="token punctuation">)</span><span class="token punctuation">;</span>
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">





<h2 id="11、连接池"><a href="#11、连接池" class="headerlink" title="11、连接池"></a>11、连接池</h2><h3 id="1、c3p0"><a href="#1、c3p0" class="headerlink" title="1、c3p0"></a>1、c3p0</h3><h4 id="2-C3P0常用的配置参数解释"><a href="#2-C3P0常用的配置参数解释" class="headerlink" title="2)C3P0常用的配置参数解释"></a>2)C3P0常用的配置参数解释</h4><table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>driverClass</td>
<td>数据库驱动类。例如：com.mysql.jdbc.Driver</td>
</tr>
<tr>
<td>jdbcUrl</td>
<td>连接数据库的url地址。例如：jdbc:mysql://localhost:3306/day05_db</td>
</tr>
<tr>
<td>user</td>
<td>连接数据库的用户名。例如：root</td>
</tr>
<tr>
<td>password</td>
<td>连接数据库的密码。例如：1234</td>
</tr>
<tr>
<td>initialPoolSize</td>
<td>刚创建好连接池的时候连接数量</td>
</tr>
<tr>
<td>maxPoolSize</td>
<td>连接池中最多可以放多少个连接</td>
</tr>
</tbody></table>
<h4 id="3-API介绍"><a href="#3-API介绍" class="headerlink" title="3)API介绍"></a>3)API介绍</h4><p><code>com.mchange.v2.c3p0.ComboPooledDataSource</code>类表示C3P0的连接池对象，常用2种创建连接池的方式：</p>
<p><code>1.无参构造，使用默认配置</code>，</p>
<p><code>2.有参构造，使用命名配置</code></p>
<ol>
<li><pre><code class="java">public ComboPooledDataSource()
无参构造使用默认配置（使用xml中default-config标签中对应的参数）
<pre class="line-numbers language-none"><code class="language-none">
2. ```java
   public ComboPooledDataSource(String configName)
   有参构造使用命名配置（configName：xml中配置的名称，使用xml中named-config标签中对应的参数）<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre></code></pre>
</li>
<li><pre><code class="java">public Connection getConnection() throws SQLException
从连接池中取出一个连接
<pre class="line-numbers language-none"><code class="language-none">
#### 4)使用步骤

1.导入jar包`c3p0-0.9.1.2.jar`

![1604479969612](https://i.loli.net/2021/09/02/ytBxZSiIChLkulb.png)

2.编写`c3p0-config.xml`配置文件，配置对应参数

~~~xml
&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
&lt;c3p0-config&gt;
    &lt;!--默认加载的数据库配置信息--&gt;
    &lt;default-config&gt;
        &lt;property name="driverClass"&gt;com.mysql.jdbc.Driver&lt;/property&gt;
        &lt;property name="jdbcUrl"&gt;jdbc:mysql:///day05_2&lt;/property&gt;
        &lt;property name="user"&gt;root&lt;/property&gt;
        &lt;property name="password"&gt;1234&lt;/property&gt;
        &lt;property name="initialPoolSize"&gt;5&lt;/property&gt;
        &lt;property name="maxPoolSize"&gt;20&lt;/property&gt;
    &lt;/default-config&gt;

    &lt;!-- 自定义数据库环境--&gt;
    &lt;named-config name="test"&gt;
        &lt;property name="driverClass"&gt;com.mysql.jdbc.Driver&lt;/property&gt;
        &lt;property name="jdbcUrl"&gt;jdbc:mysql:///day05_3&lt;/property&gt;
        &lt;property name="user"&gt;root&lt;/property&gt;
        &lt;property name="password"&gt;1234&lt;/property&gt;
        &lt;property name="initialPoolSize"&gt;5&lt;/property&gt;
        &lt;property name="maxPoolSize"&gt;20&lt;/property&gt;
    &lt;/named-config&gt;
&lt;/c3p0-config&gt;
~~~



3.将配置文件放在src目录下

![1604480612382](https://i.loli.net/2021/09/02/4iacx5XP6BJjKtU.png)

4.创建**连接池对象`ComboPooledDataSource`，**使用默认配置或命名配置

~~~java
        //创建数据源(连接池对象)对象，自动加载src根路径下c3p0-config.xml
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
~~~



5.从连接池中获取连接对象

~~~java
        //获取连接对象
        Connection conn = dataSource.getConnection();
~~~

6.使用连接对象操作数据库,查询表中所有数据并输出到控制台。

~~~java
        //3)创建发送sql的对象
        Statement stm = conn.createStatement();
        //4)发送sql语句，获取ResultSet结果集
        String selectSql="select * from user";
        ResultSet rs = stm.executeQuery(selectSql);
        //5)解析结果集
        ArrayList&lt;User&gt; users = new ArrayList&lt;&gt;();
        while (rs.next()){
            int id=rs.getInt(1);
            String name=rs.getString("username");
            String password=rs.getString(3);
            User user = new User();
            user.setId(id);
            user.setPassword(password);
            user.setUserName(name);
            users.add(user);
        }
        System.out.println(users);
~~~



6.关闭资源，归还连接

~~~java
        //6)close 归还连接对象到连接池
        rs.close();
        stm.close();
        conn.close();
~~~

#### 注意事项

C3P0配置文件名称必须为`c3p0-config.xml`
C3P0命名配置可以有多个







### 16.4 Druid连接池

#### 1)Druid简介

​	Druid是阿里巴巴开发的号称为监控而生的数据库连接池(可以监控访问数据库的性能)**，Druid是目前最好的数据库连接池**。在功能、性能、扩展性方面，都超过其他数据库连接池。Druid已经在阿里巴巴部署了超过600个应用，经过一年多生产环境大规模部署的严苛考验。如：一年一度的双十一活动，每年春运的抢火车票。

~~~tex
Druid的下载地址：&lt;https://github.com/alibaba/druid&gt;  
Druid连接池使用的jar包：druid-1.0.9.jar
~~~

#### 2)Druid常用的配置参数

| **url**             | **数据库**连接字符串**jdbc:mysql://localhost:3306/数据库名** |
| ------------------- | ------------------------------------------------------------ |
| **username**        | **数据库的用户名**                                           |
| **password**        | **数据库的密码**                                             |
| **driverClassName** | **驱动类名。根据url自动识别，这一项可配可不配，如果不配置druid会根据url自动识别数据库的类型，然后选择相应的数据库驱动名** |
| **initialSize**     | **初始化时建立的物理连接的个数。初始化发生在显式调用init方法，或者第一次获取连接对象时** |
| **maxActive**       | **连接池中最大连接数**                                       |
| **maxWait**         | **获取连接时最长等待时间，单位是毫秒。**                     |

#### 3)Druid连接池基本使用

##### API介绍

核心类：**DruidDataSourceFactory**

获取数据源的方法：使用**com.alibaba.druid.pool.DruidDataSourceFactory**类中的静态方法：

```java
public static DataSource createDataSource(Properties properties)
-- 创建一个连接池，连接池的参数使用properties中的数据<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</code></pre>
</li>
</ol>
<p>配置信息在properties属性对象中。</p>
<p>我们可以看到Druid连接池在创建的时候需要一个Properties对象来设置参数，所以我们使用properties文件来保存对应的参数。</p>
<p>Druid连接池的配置文件名称随便，放到src目录或者项目根目录下面加载<br><code>druid.properties</code>文件内容：</p>
<pre class="line-numbers language-properties" data-language="properties"><code class="language-properties"><span class="token comment"># 数据库连接参数</span>
<span class="token attr-name">url</span><span class="token punctuation">=</span><span class="token attr-value">jdbc:mysql://localhost:3306/day05_db</span>
<span class="token attr-name">username</span><span class="token punctuation">=</span><span class="token attr-value">root</span>
<span class="token attr-name">password</span><span class="token punctuation">=</span><span class="token attr-value">123</span>
<span class="token attr-name">driverClassName</span><span class="token punctuation">=</span><span class="token attr-value">com.mysql.jdbc.Driver</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="4-使用步骤"><a href="#4-使用步骤" class="headerlink" title="4)使用步骤"></a>4)使用步骤</h4><ol>
<li>导入核心包druid-1.0.9.jar</li>
</ol>
<p><img src="https://i.loli.net/2021/09/02/XgTbLcVoeCEhwWt.png" alt="1604481946087"></p>
<ol start="2">
<li>在项目下创建一个properties文件，文件名随意，设置对应参数</li>
</ol>
<pre class="line-numbers language-properties" data-language="properties"><code class="language-properties"><span class="token comment"># 数据库连接参数</span>
<span class="token attr-name">url</span><span class="token punctuation">=</span><span class="token attr-value">jdbc:mysql://localhost:3306/day05_2</span>
<span class="token attr-name">username</span><span class="token punctuation">=</span><span class="token attr-value">root</span>
<span class="token attr-name">password</span><span class="token punctuation">=</span><span class="token attr-value">1234</span>
<span class="token attr-name">driverClassName</span><span class="token punctuation">=</span><span class="token attr-value">com.mysql.jdbc.Driver</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ol start="3">
<li>加载properties文件的内容到Properties对象中</li>
</ol>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//加载properties文件构建配置对象</span>
<span class="token class-name">InputStream</span> in <span class="token operator">=</span> <span class="token class-name">DruidTest</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getResourceAsStream</span><span class="token punctuation">(</span><span class="token string">"druid.properties"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Properties</span> properties <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Properties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
properties<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span>in<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<ol start="4">
<li>创建DRUID连接池，使用配置文件中的参数</li>
</ol>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//使用DruidDataSourceFactory工厂类构建连接池对象</span>
       <span class="token class-name">DataSource</span> dataSource <span class="token operator">=</span> <span class="token class-name">DruidDataSourceFactory</span><span class="token punctuation">.</span><span class="token function">createDataSource</span><span class="token punctuation">(</span>properties<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<ol start="5">
<li>从DRUID连接池中取出连接</li>
</ol>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//获取连接对象</span>
<span class="token class-name">Connection</span> conn <span class="token operator">=</span> dataSource<span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<ol start="6">
<li><p>执行SQL语句</p>
</li>
<li><p>关闭资源,归还连接</p>
</li>
</ol>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//6.归还资源</span>
conn<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>



<p>案例代码:</p>
<p>步骤1:属性文件：在项目下新建一个druid配置文件，命名为：druid.properties </p>
<pre class="line-numbers language-properties" data-language="properties"><code class="language-properties"><span class="token attr-name">url</span><span class="token punctuation">=</span><span class="token attr-value">jdbc:mysql:///day05_1</span>
<span class="token attr-name">username</span><span class="token punctuation">=</span><span class="token attr-value">root</span>
<span class="token attr-name">password</span><span class="token punctuation">=</span><span class="token attr-value">1234</span>
<span class="token attr-name">driverClassName</span><span class="token punctuation">=</span><span class="token attr-value">com.mysql.jdbc.Driver</span>
<span class="token attr-name">initialSize</span><span class="token punctuation">=</span><span class="token attr-value">5</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>步骤2:java代码:</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">{</span>
    <span class="token comment">//加载properties文件构建配置对象</span>
    <span class="token class-name">InputStream</span> in <span class="token operator">=</span> <span class="token class-name">DruidTest</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getResourceAsStream</span><span class="token punctuation">(</span><span class="token string">"druid.properties"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Properties</span> properties <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Properties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    properties<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span>in<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//获取连接池对象</span>
    <span class="token class-name">DataSource</span> dataSource <span class="token operator">=</span> <span class="token class-name">DruidDataSourceFactory</span><span class="token punctuation">.</span><span class="token function">createDataSource</span><span class="token punctuation">(</span>properties<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//获取连接对象</span>
    <span class="token class-name">Connection</span> conn <span class="token operator">=</span> dataSource<span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//2.获取发送sql的对象</span>
    <span class="token class-name">Statement</span> stm <span class="token operator">=</span> conn<span class="token punctuation">.</span><span class="token function">createStatement</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//4.发送select语句</span>
    <span class="token class-name">String</span> sql<span class="token operator">=</span><span class="token string">"select * from user"</span><span class="token punctuation">;</span>
    <span class="token class-name">ResultSet</span> rs <span class="token operator">=</span> stm<span class="token punctuation">.</span><span class="token function">executeQuery</span><span class="token punctuation">(</span>sql<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//5.解析结果集</span>
    <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">User</span><span class="token punctuation">&gt;</span></span> users <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span>rs<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">int</span> id <span class="token operator">=</span> rs<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> username <span class="token operator">=</span> rs<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> password <span class="token operator">=</span> rs<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">User</span> user <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">User</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        user<span class="token punctuation">.</span><span class="token function">setId</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>
        user<span class="token punctuation">.</span><span class="token function">setUserName</span><span class="token punctuation">(</span>username<span class="token punctuation">)</span><span class="token punctuation">;</span>
        user<span class="token punctuation">.</span><span class="token function">setPassword</span><span class="token punctuation">(</span>password<span class="token punctuation">)</span><span class="token punctuation">;</span>
        users<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>users<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//调用close归还连接对象</span>
    rs<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    stm<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    conn<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">

<p>总结：</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">1)jdbc开发流程：
  1.注册驱动
    Class.forName(驱动类的全限定名称);
  2.获取连接对象
    conn=DriverManager.getConnection(url,user,pwd);
  3.获取发送sql的对象
    pstm= conn.prepareStatement(sql模板);//防止sql注入
    stm=conn.createStatement();//会有sql注入的问题
    CallableStatement cstm=conn.prepareCall("{call 存储过程名称（？，？，...）}");
  4.发送参数或者sql
    1）发送sql: executeQuery(sql);// select
               executeUpdate(sql);// insert delete update
               execute();
    2)发送参数
              //设置参数
              比如：pstm.setXX(参数索引位，值)；
              executeQuery();
              executeUpdate();
   5.结果相应
         1）返回受影响的行数
         2）返回结果集ResultSet
                next();true/false
                getXX(字段索引位，从1开始);
                getXX(字段名称);
    6.释放资源，关闭连接
      rs.close();
      stm.close();
      conn.close();
2)jdbc之事务
  jdbc默认事务自动提交；
  conn.setAutoCommit(false);//设置事务手动提交
  conn.commit();
  conn.rollback();
3)连接池
  常用的参数：
    1）数据库的4大参数-- url driverclass user pwd
    2) 初始化大小 最大连接数 最小连接数 等待时间等
   
     

      <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><h3 id="1-什么是jdbc"><a href="#1-什么是jdbc" class="headerlink" title="1.什么是jdbc?"></a>1.什么是jdbc?</h3><pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">jdbc就是java操纵数据库的接口规范，具体的实现由不同的数据库厂商去实现；
对我开发人员来说，只关注接口提供的功能即可；
说白了，jdbc就是java连接数据库的一个桥梁；<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h3 id="2-以查询为例，jdbc开发流程？"><a href="#2-以查询为例，jdbc开发流程？" class="headerlink" title="2.以查询为例，jdbc开发流程？"></a>2.以查询为例，jdbc开发流程？</h3><pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">1.注册驱动
	3种注册方式：
		显示注册： DriverManager.registerDriver(new Driver());
		        弊端：会导致驱动对象被注册2次，浪费内存；
		隐式注册： Class.forName(com.mysql.jdbc.Driver"");
        		好处：驱动对象只注册一次
        自动注册： 基于Java的SPI机制，自动注册
2.获取连接对象
    Connection conn= DriverManger.getConnection(url,userName,password);
     	关注点：url格式===》jdbc:mysql://ip:端口/数据库名称
3.获取发送SQL语句的对象
	 Statement stm=conn.createStatement();
4.发送sql
	增删改： int count= stm.executeUpdate(sql);返回受影响的行数
	查询：ResultSet rs=stm.executeQuery(sql);返回结果集，被ResultSet封装
	ResultSet核心API: 
		 boolean isHashNextLine=rs.next();//如果有下一行，返回true,否则返回false
		 rs.getXXX(字段索引位)或者rs.getXXX(字段名称)；//字段索引位从1开始
5.释放资源，关闭连接
	3个close;
		rs.close();
		stm.close();
		conn.close();<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="3-预编译对象PreparedStatement"><a href="#3-预编译对象PreparedStatement" class="headerlink" title="3.预编译对象PreparedStatement"></a>3.预编译对象PreparedStatement</h3><p>好处：1.避免了SQL注入 2.提高了SQL的复用性；</p>
<p>使用流程：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">PreparedStatement pstm<span class="token operator">=</span>conn<span class="token punctuation">.</span>prepareStatement<span class="token punctuation">(</span><span class="token keyword">SQL</span>模板<span class="token punctuation">)</span>
<span class="token keyword">SQL</span>模板中参数以问号？作为占位符，问号是第几个，那么入参的索引位就是几；
eg:<span class="token keyword">select</span> <span class="token operator">*</span><span class="token keyword">from</span> <span class="token keyword">user</span> <span class="token keyword">where</span> name<span class="token operator">=</span>? <span class="token operator">and</span> password<span class="token operator">=</span>?<span class="token punctuation">;</span>
设置参数
pstm<span class="token punctuation">.</span>setXXX<span class="token punctuation">(</span>参数索引位，参数值<span class="token punctuation">)</span><span class="token punctuation">;</span>
执行查询
<span class="token keyword">int</span> count<span class="token operator">=</span>pstm<span class="token punctuation">.</span>executeUpdate（）；返回值表示受影响行数
ResultSet rs<span class="token operator">=</span> pstm<span class="token punctuation">.</span>executeQuery<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<table>
<thead>
<tr>
<th>比较</th>
<th>StatemenT</th>
<th>pREPAREDsTATEMENT(预编译对象)</th>
</tr>
</thead>
<tbody><tr>
<td>是否SQL注入</td>
<td>有</td>
<td>无</td>
</tr>
<tr>
<td>是否预编译</td>
<td>无</td>
<td>有</td>
</tr>
<tr>
<td>执行效率</td>
<td>单个SQL执行，效率较高</td>
<td>相同的SQL多次执行，效率较高</td>
</tr>
</tbody></table>
<h3 id="4-连接池"><a href="#4-连接池" class="headerlink" title="4.连接池"></a>4.连接池</h3><p>好处：避免了连接对象被反复的创建与销毁带来的性能开销；</p>
<h4 id="1-C3P0"><a href="#1-C3P0" class="headerlink" title="1.C3P0"></a>1.C3P0</h4><pre class="line-numbers language-SQL" data-language="SQL"><code class="language-SQL">1.导入依赖包：c3p0-0.9.1.2.jar、mchange-commons-java-0.2.12.jar
2.定义xml配置文件（名字必须叫c3p0-config.xml，而且存放在类的根路径下）
   配置：&lt;default-config&gt;内部的配置，默认被加载
3.构建连接池对象
	 ComboPooledDataSource dataSource = new ComboPooledDataSource();
	  Connection conn = dataSource.getConnection();<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="2-Druid"><a href="#2-Druid" class="headerlink" title="2.Druid"></a>2.Druid</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1.</span>导入jar资源：druid<span class="token operator">-</span><span class="token number">1.0</span><span class="token number">.9</span><span class="token punctuation">.</span>jar
<span class="token number">2.</span>配置数据源的连接参数，一般配置在properties文件中：
	username<span class="token operator">=</span>root
	password<span class="token operator">=</span>root
	url<span class="token operator">=</span>jdbc:mysql:<span class="token comment">//192.168.188.130:3306/day05_1</span>
	driverClassName<span class="token operator">=</span>com<span class="token punctuation">.</span>mysql<span class="token punctuation">.</span>jdbc<span class="token punctuation">.</span>Driver
	注意：<span class="token keyword">key</span>不能乱写
<span class="token number">3.</span>将配置文件转化成文件流对象，然后被Proerties对象<span class="token keyword">load</span>加载，然后最终被连接池工厂加载，构建连接池对象；
        DataSource dataSource <span class="token operator">=</span> DruidDataSourceFactory<span class="token punctuation">.</span>createDataSource<span class="token punctuation">(</span>props<span class="token punctuation">)</span><span class="token punctuation">;</span>
        Connection conn <span class="token operator">=</span> dataSource<span class="token punctuation">.</span>getConnection<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>




                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Long</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://ergou15154.gitee.io/posts/8fe47ff4.html">https://ergou15154.gitee.io/posts/8fe47ff4.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Long</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/JDBC/">
                                    <span class="chip bg-color">JDBC</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="qq,qzone,wechat,weibo,twitter,facebook,google,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/null" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/null" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    .v[data-class="v"] .vwrap .vheader .vinput {
      width: 32%;
      border-bottom: 1px dashed #dedede;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
let metaPlaceholder = {"nick":"昵称/QQ号(必填)","mail":"邮箱(必填)","link":"网址(https://)"} ;
//这里要换行
new Valine({
        el: '#vcomments',
        appId: 'Ucrxxxxxxxxxxxxxxxx-xxxxsz',
        appKey: 'zPsLxxxxxxxxxxxxxxerLmd',
        notify: 'true' === 'true',
        verify: 'true' === 'true',
        visitor: 'true' === 'true',
        avatar: 'monsterid',
        pageSize: '10',
        lang: 'zh-CN',
        placeholder: '留下你的足迹..',
        meta: ["nick", "mail", "link"],
        recordIP: 'true' === 'true',
        enableQQ: 'monsterid',
        requiredFields: ["d142de78a3402022b268b12dab90d819"],
        master: ["d142de78a3402022b268b12dab90d819"],
        friends: ["cb3e577ff029d6073400d5557effd41f", ""],
        tagMeta: ["博主", "小伙伴", "访客"],
        metaPlaceholder: metaPlaceholder,

    });

    document.body.addEventListener('click', function(e) {
        if (e.target.classList.contains('vsubmit')) {
            const email = document.querySelector('input[type=email]');
            const nick = document.querySelector('input[name=nick]');
            const reg = /^[A-Za-z0-9_-\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            if (!email.value || !nick.value || !reg.test(email.value)) {
                const str = `<div class="valert txt-center"><div class="vtext">请填写正确的昵称和邮箱！</div></div>`;
                const vmark = document.querySelector('.vmark');
                vmark.innerHTML = str;
                vmark.style.display = 'block';

                e.stopPropagation();

                setTimeout(function() {
                    vmark.style.display = 'none';
                    vmark.innerHTML = '';
                }, 2500);
            }
        }
        }, true);
</script>



    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/477c31c6.html">
                    <div class="card-image">
                        
                        <img src="/medias/banner/3.jpg" class="responsive-img" alt="02分组函数+DCL+约束+多表查询+三大范式">
                        
                        <span class="card-title">02分组函数+DCL+约束+多表查询+三大范式</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            分组函数+DCL+约束+多表查询+三大范式
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-15
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="post-category">
                                    数据库
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">
                        <span class="chip bg-color">数据库</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/8086094.html">
                    <div class="card-image">
                        
                        <img src="/medias/banner/13.jpg" class="responsive-img" alt="MyBatisPlus">
                        
                        <span class="card-title">MyBatisPlus</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-15
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/MyBatisPlus/" class="post-category">
                                    MyBatisPlus
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/MyBatisPlus/">
                        <span class="chip bg-color">MyBatisPlus</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: Long<br />'
            + '文章作者: Long<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="tencent"
                   type="playlist"
                   id="1776127550"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2021</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">Long</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">155.8k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "10";
                    var startDate = "25";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn/" target="_blank">闽ICP备xxxxxxx号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/vegetable-dog16546/" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1694162702@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1694162702" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1694162702" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>



    <a href="6788560391" class="tooltipped" target="_blank" data-tooltip="关注我的微博: 6788560391" data-position="top" data-delay="50">
        <i class="fab fa-weibo"></i>
    </a>





    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lightgallery/1.6.11/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?aaa6c944b0ed07922901d7fc571a171d";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

<!-- 深色模式按钮 -->
    <script>
        if (localStorage.getItem('dark') === '1') {
        document.body.classList.add('dark');
        }
        else if (new Date().getHours() >= 22 || new Date().getHours() < 7) {
        document.body.classList.add('dark');
        } 
        else if (matchMedia('(prefers-color-scheme: dark)').matches) {
        document.body.classList.add('dark');
        }
    </script>
    <a onclick="switchNightMode()" id="sma">
        <i class="fas fa-lightbulb" id="nightMode" aria-hidden="true"></i>
    </a>

    <!-- 天气接口控件   -->
    
        <script type="text/javascript">
        WIDGET = {FID: 'zLkJSQpqsh'}
        </script>
    <!-- <script type="text/javascript" src="https://apip.weatherdt.com/float/static/js/r.js?v=1111"></script> -->

    <script type="text/javascript">
      var windowWidth = $(window).width();
      if (windowWidth > 768) {
          document.write('<script type="text/javascript" src="https://apip.weatherdt.com/float/static/js/r.js?v=1111"><\/script>');
      }
    </script>
    

    
    <script>
        (function (i, s, o, g, r, a, m) {
            i["DaoVoiceObject"] = r;
            i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o), m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            a.charset = "utf-8";
            m.parentNode.insertBefore(a, m)
        })(window, document, "script", ('https:' == document.location.protocol ? 'https:' : 'http:') +
            "//widget.daovoice.io/widget/6984b559.js", "daovoice")
        daovoice('init', {
            app_id: "4xxxxxxxe"
        });
        daovoice('update');
    </script>
    

	
    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
